'use strict';
const fs = require('fs')

const inquirer = require('inquirer')
const fse = require('fs-extra')
const semver = require('semver')

const Command = require('@ting-cli-dev/command')
const log = require('@ting-cli-dev/log')

const getProjectTemplate = require('./getProjectTemplate')


const TYPE_PROJECT = 'project'
const TYPE_COMPONENT = 'component'

class initCommand extends Command {
    init() {
        this.projectName = this._argv[0]
        this.force = (this._argv[1] && this._argv[1].force)|| false
        this.noUpdate = (this._argv[1] && this._argv[1].noUpdate) || false
        log.verbose('projectName: ', this.projectName)
        log.verbose('force: ', this.force)
        log.verbose('noUpdate: ', this.noUpdate)
    }

    async exec() {
        try {
            // 1. 准备阶段
            const projectInfo = await this.prepare()
            this.projectInfo = projectInfo
            if (projectInfo) {
                // 2. 下载模板
                this.downloadTemplate();
                // 3. 安装模板
            }
            
        } catch (error) {
            log.error(error.message)
        }
       
    }

    async prepare() {
        const localPath = process.cwd()
        console.log(localPath, 'localPath');

        const templateData = await getProjectTemplate()
        this.template = templateData
        
        // 1. 判断当前目录是否为空
        const res = this.isCwdDirEmpty(localPath)
        // 2. 是否启动强制更新
        if (!res) {
            let ifContinue = false;
            if (!this.force) {
                ifContinue = (await inquirer.prompt({
                    type: 'confirm',
                    name: 'ifContinue',
                    default: false,
                    message: '当前文件夹不为空，是否继续创建项目'
                })).ifContinue

                if (!ifContinue) {
                    return;
                }
            }
            
            if (ifContinue || this.force) {
                // 清空文件夹前给用户做二次确认
                const { isConfirmDelete } = await inquirer.prompt({
                    type: 'confirm',
                    name: 'isConfirmDelete',
                    default: false,
                    message: '确认清空当前文件夹下的文件？'
                })
                // 清空当前文件夹
                if (isConfirmDelete) {
                    fse.emptyDirSync(localPath)
                }
                
            }
        }

        return await this.getProjectInfo()
    }
    
    async getProjectInfo() {
        // 3. 选择创建项目或组件
        const { type } = await inquirer.prompt({
            type: 'list',
            name: 'type',
            default: TYPE_PROJECT,
            message: '请选择要创建的项目类型',
            choices: [
                {
                    name: '项目',
                    value: TYPE_PROJECT
                },
                {
                    name: '组件',
                    value: TYPE_COMPONENT
                }
            ]
        })
        if (type === TYPE_PROJECT) {
            const projectInfo = await inquirer.prompt([
                {
                    type: 'input',
                    name: 'projectName',
                    default: '',
                    message: "请输入项目名称",
                    validate: function(v) {
                        const done = this.async();
                        setTimeout(function() {
                            if (!/^[a-zA-Z]+([-][a-zA-Z][a-zA-Z0-9]*|[_][a-zA-Z][a-zA-Z0-9]*|[a-zA-Z0-9])*$/.test(v)) {
                                done(`请输入合法项目名称:
                                1. 首字母必须是英文字符
                                2. 尾字符必须是英文或数字，不能为字符
                                3. 字符仅允许 ‘-_’
                                `);
                                return;
                            }
                            done(null, true);
                        }, 0);
                    }
                },
                {
                    type: 'input',
                    name: 'projectVersion',
                    default: '',
                    message: "请输入项目版本号",
                    validate: function (v) {
                        const done = this.async();
                        setTimeout(function() {
                            if (!semver.valid(v)) {
                                done(`请输入合法版本号: [v]x.x.x`);
                                return;
                            }
                            done(null, true);
                        }, 0);
                    },
                    filter: function(v) {
                        if (!!semver.valid(v)) {
                            return semver.valid(v)
                        } else {
                            return v
                        }
                    }
                },
                {
                    type: 'list',
                    name: 'projectTemplate',
                    message: "请输入要选择的模板",
                    choices: this.createTemplateChoice()
                }
            ])
            return {...projectInfo, type}
        }
        
    }

    isCwdDirEmpty(localPath) {
        let files = fs.readdirSync(localPath)
        files = files.filter(fileItem => {
            // 排除隐藏文件 和 node_modules
            return !fileItem.startsWith('.') && fileItem !== 'node_modules'
        })
        console.log(files, 'files');
        if (files.length > 0) {
            return false
        }
        return true
        
    }

    createTemplateChoice() {
        return this.template.map(item => {
            return {
                name: item.name,
                value: item.npmName
            }
        })
    }

    async downloadTemplate() {
        // 1. 通过项目模板API获取项目的模板信息
        
        
        const templateItem = this.template.find(item => item.npmName === this.projectInfo.projectTemplate)
        console.log(this.projectInfo, templateItem, 'data====templateItem');
        // 1.1 通过egg.js 搭建一套后端系统
        // 1.2 通过 NPM 存储项目模版
        // 1.3 将项目模版信息存储到 mongodb 数据库中
        // 1.4 通过 egg.js 获取mongodb中的数据并通过API返回
    }
    

}

function init(argv) {
    // 不建议这么拿  command.parent._optionValues.targetPath
    // console.log('init5555',argv);
    return new initCommand(argv)
}

module.exports = init;
module.exports.initCommand = initCommand;
